#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>

namespace ns_task
{
    class Task
    {
    private:
        int sock_;

    public:
        Task() //消费者获取任务使用无参构造
            : sock_(-1)
        {
        }
        Task(int sock) //生产者消费任务需要有参构造
            : sock_(sock)
        {
        }
        int Run()
        {
            char buffer[1024];
            memset(buffer, 0, sizeof(buffer));
            ssize_t s = read(sock_, buffer, sizeof(buffer) - 1);
            if (s > 0)
            {
                buffer[s] = 0; //把获取的内容当成字符串
                //打印获取到的信息
                std::cout << "client#" << buffer << std::endl;

                //服务端获取信息后回显给客户端
                std::string echo_string = ">>>server<<<,";
                echo_string += buffer;

                write(sock_, echo_string.c_str(), echo_string.size());
            }
            else if (s == 0)
            {
                std::cout << "client quit ..." << std::endl;
            }
            else
            {
                std::cerr << "read error." << std::endl;
            }

            //执行完任务后关闭对应文件描述符
            close(sock_);
        }
        int operator()()
        {
            return Run();
        }
        ~Task()
        {
        }
    };
}